package com.king.first.app.timer;

import com.king.first.bean.WaterSensor;
import com.king.first.utils.ContentUtils;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;
import org.apache.flink.util.OutputTag;

import java.time.Duration;
import java.util.HashMap;
import java.util.Map;

/**
 * 监控水位传感器的水位值，如果水位值在五分钟之内(processing time)连续上升，则报警。
 */
public class Flink_Time_Alarms {

    public static void main(String[] args) {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        SingleOutputStreamOperator<WaterSensor> waterSensorStream = env
                .socketTextStream(ContentUtils.HOST, 9999)  // 在socket终端只输入毫秒级别的时间戳
                .map(new MapFunction<String, WaterSensor>() {
                    @Override
                    public WaterSensor map(String value) throws Exception {
                        String[] datas = value.split(",");
                        return new WaterSensor(datas[0], Long.valueOf(datas[1]), Integer.valueOf(datas[2]));

                    }
                });

        WatermarkStrategy<WaterSensor> watermarkStrategy = WatermarkStrategy.<WaterSensor>forBoundedOutOfOrderness(Duration.ofSeconds(2));

        SingleOutputStreamOperator<WaterSensor> streamOperator = waterSensorStream.assignTimestampsAndWatermarks(watermarkStrategy)
                .keyBy(value -> value.getId())
                .process(new KeyedProcessFunction<String, WaterSensor, WaterSensor>() {

                    private WaterSensor old = null;
                    private Map<String, WaterSensor> wsMap = new HashMap<>();
                    private Map<String, Long> tsMap = new HashMap<>();

                    @Override
                    public void processElement(WaterSensor value, KeyedProcessFunction<String, WaterSensor, WaterSensor>.Context ctx, Collector<WaterSensor> out) throws Exception {

                        Long ts = ctx.timerService().currentProcessingTime() + 10000;
                        String id = value.getId();
                        wsMap.put(id, value);

                        if (old == null) {
                            old = value;
                            tsMap.put(id, ts);
                            ctx.timerService().registerProcessingTimeTimer(ts);
                        } else if (old.getVc() <= value.getVc()) {
                            old = value;
                        } else if (old.getVc() > value.getVc()) {
                            Long oldTs = tsMap.get(id);
                            ctx.timerService().deleteProcessingTimeTimer(oldTs);
                            old = null;
                        }

                        out.collect(value);
                    }

                    @Override
                    public void onTimer(long timestamp, KeyedProcessFunction<String, WaterSensor, WaterSensor>.OnTimerContext ctx, Collector<WaterSensor> out) throws Exception {
                        ctx.output(new OutputTag<WaterSensor>("alarm"){}, wsMap.get(ctx.getCurrentKey()));
                    }
                });

        streamOperator.print();
        streamOperator.getSideOutput(new OutputTag<WaterSensor>("alarm"){}).print("alarm:");

        try {
            env.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
